package com.ssm.zy.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.MalformedParameterizedTypeException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

//阿里云 OSS 工具类

public class OSSUtil {

    private static String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    private static String accessKeyId = "LTAI5t8dpRZCvohMFBhXdfy3";
    private static String accessKeySecret = "KXiAObMtlBFYbp3dM75Drk4N0AoXsN";
    private static String bucketName = "little-yellow-book";

    public static String storageFile(MultipartFile multipartFile) throws IOException {
        //获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();

        //避免文件覆盖
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss"))+multipartFile.getOriginalFilename();

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        ossClient.putObject(bucketName,fileName,inputStream);

        //文件访问路径
        String url = endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+fileName;
        //关闭ossClient
        ossClient.shutdown();
        return url;//把上传到oss的路径返回
    }
}
